package cn.lycode.framework.event;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.lycode.common.event.SessionChangeMeta;
import cn.lycode.common.event.SessionChangeEvent;
import cn.lycode.framework.constant.FrameworkConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

import static cn.lycode.framework.constant.FrameworkConstant.SESSION_KEY_ROLE_PREFIX;

/**
 * @ClassName EventListener 事件监听器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class GlobalEventListener {

    /**
     * 监听到 PermsChangeEvent事件就会执行
     * 清空缓存的 当前角色对应的菜单列表和权限列表
     * 菜单列表：根据角色菜单表查出的此角色拥有的菜单
     * 权限列表：所有拥有的菜单中的权限标识
     * @param event
     */
    @EventListener
    public void handleSessionChangeEvent(SessionChangeEvent event) {
        SessionChangeMeta sessionChangeMeta = event.getPayload();
        log.info("[事件监听]-权限Session变更, data: {}", sessionChangeMeta);
        List<?> roleFlags = sessionChangeMeta.getRoleFlagList();

        for (Object roleFlag : roleFlags) {
            SaSession roleSession = SaSessionCustomUtil.getSessionById(SESSION_KEY_ROLE_PREFIX + roleFlag);
            roleSession.delete(FrameworkConstant.SESSION_KEY_PERMS_LIST);
            roleSession.delete(FrameworkConstant.SESSION_KEY_MENU_LIST);
        }

        List<?> userIdList = sessionChangeMeta.getUserIdList();
        for (Object userId : userIdList) {
            SaSession session = StpUtil.getSessionByLoginId(userId);
            session.delete(FrameworkConstant.SESSION_KEY_ROLE_LIST);
        }

    }


}
